package com.jhx.mall.util;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * BaseServlet
 *
 * @author hyl
 * @date 2024-11-04
 */
public class BaseServlet<T> extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void init() throws ServletException {

    }

    protected void ok(HttpServletRequest request , HttpServletResponse response,
                      T data) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        R result =  R.ok(data);
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    public void error(HttpServletRequest request , HttpServletResponse response,
                   T data) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        R result = R.fail(data);
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
}
